﻿using Ookii.Dialogs.Wpf;
using Syncfusion.UI.Xaml.TreeGrid.Converter;
using Syncfusion.UI.Xaml.TreeGrid;
using Syncfusion.XlsIO;
using System.IO;
using System.Windows;
using Common.Client.Lib.Extensions;
using Common.Lib.Helper;
using Common.Lib.Localization;
using Common.Mvvm.Dialogs;

namespace Syncfusion.Lib.Controls.Attach
{
    /// <summary>
    /// <see cref="SfTreeGridExportToExcel"/> 导出到Excel的附加属性
    /// </summary>
    public class SfTreeGridExportToExcel
    {

        #region 默认文件名称 - 依赖属性
        /// <summary>
        /// 默认文件名称 - 获取依赖属性
        /// </summary>                
        public static string GetDefaultFileName(DependencyObject obj)
        {
            return (string)obj.GetValue(DefaultFileNameProperty);
        }

        /// <summary>
        /// 默认文件名称 - 设置依赖属性
        /// </summary>  
        public static void SetDefaultFileName(DependencyObject obj, string value)
        {
            obj.SetValue(DefaultFileNameProperty, value);
        }

        /// <summary>
        /// 默认文件名称 - 注册依赖属性 
        /// <para>使用DependencyProperty作为MyProperty的后台存储。这支持动画、样式、绑定等。</para>
        /// </summary>
        public static readonly DependencyProperty DefaultFileNameProperty =
            DependencyProperty.RegisterAttached("DefaultFileName", typeof(string), typeof(SfTreeGridExportToExcel), new PropertyMetadata(null));

        #endregion 默认文件名称 - 依赖属性

        #region 数据源 - 依赖属性
        /// <summary>
        /// 数据源 - 获取依赖属性
        /// </summary>                
        public static SfTreeGrid GetDataSource(DependencyObject obj)
        {
            return (SfTreeGrid)obj.GetValue(DataSourceProperty);
        }

        /// <summary>
        /// 数据源 - 设置依赖属性
        /// </summary>  
        public static void SetDataSource(DependencyObject obj, SfTreeGrid value)
        {
            obj.SetValue(DataSourceProperty, value);
        }

        /// <summary>
        /// 数据源 - 注册依赖属性 
        /// <para>使用DependencyProperty作为MyProperty的后台存储。这支持动画、样式、绑定等。</para>
        /// </summary>
        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.RegisterAttached("DataSource", typeof(SfTreeGrid), typeof(SfTreeGridExportToExcel), new FrameworkPropertyMetadata(null, OnDataSourceChanged));


        /// <summary>
        /// 当 数据源 - 附加属性发生变更时
        /// </summary>
        private static void OnDataSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is FrameworkElement fe)
            {
                if (e.NewValue != null)
                {
                    fe.Loaded += Fe_Loaded;
                }
                else
                {
                    fe.Loaded -= Fe_Loaded;
                    fe.Unloaded -= Fe_Unloaded;
                    fe.PreviewMouseLeftButtonDown -= Fe_MouseLeftButtonDown;
                }
            }
        }

        private static void Fe_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (sender is FrameworkElement fe)
            {
                try
                {
                    var dataSourceObj = fe.GetValue(DataSourceProperty);
                    string? defaultFileName = fe.GetValue(DefaultFileNameProperty) as string;
                    if (string.IsNullOrEmpty(defaultFileName))
                    {
                        defaultFileName = $"{AppTime.Now.ToString("yyyyMMdHHmmss.xlsx")}";
                    }
                    if (dataSourceObj is SfTreeGrid sfTreeGrid)
                    {
                        VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog();
                        saveFileDialog.Title = LocalizationResource.GetResourceValue("请选择导出文件保存的路径", isReturnNoResourceValueParcelString: false);
                        saveFileDialog.AddExtension = true;
                        saveFileDialog.FileName = defaultFileName;
                        saveFileDialog.DefaultExt = "*.xlsx";
                        saveFileDialog.Filter = LocalizationResource
                            .GetResourceValue("Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls|CSV (逗号分割)(*.csv)|*.csv", isReturnNoResourceValueParcelString: false);
                        var saveFileDialogRes = saveFileDialog.ShowDialog(Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive));
                        if (saveFileDialogRes == true)
                        {
                            string saveFilePath = saveFileDialog.FileName;
                            if (!string.IsNullOrWhiteSpace(saveFilePath))
                            {
                                var options = new TreeGridExcelExportingOptions();
                                //根据文件扩展名指定Excel的版本
                                if (Path.GetExtension(saveFilePath).ToLower() == ".xls")
                                {
                                    options.ExcelVersion = ExcelVersion.Excel97to2003;
                                }
                                else
                                {
                                    options.ExcelVersion = ExcelVersion.Xlsx;
                                }
                                //排除MappingName=""的列
                                options.ExcludeColumns.Add("");
                                options.ExcludeColumns.Add("NullMappingName");
                                //导出禁用 Excel 中的大纲 默认为true 
                                options.AllowOutliningGroups = true;
                                //导出显示文本
                                options.TreeGridExportMode = TreeGridExportMode.Text;
                                //导出堆叠标题
                                options.ExportStackedHeaders = true;
                                //导出超链接 默认为true
                                options.CanExportHyperLink = true;
                                //导出具有实际列宽的列，默认为true
                                options.ExportColumnWidth = true;
                                //不带网格线的树网格导出到 Excel 属性的默认值为true
                                options.IsGridLinesVisible = true;
                                //使用缩进列来表示节点级别 默认为false
                                options.AllowIndentColumn = true;

                                var excelEngine = sfTreeGrid.ExportToExcel(options);
                                if (excelEngine?.Excel?.Workbooks?.Count > 0)
                                {
                                    var workBook = excelEngine.Excel.Workbooks[0];
                                    //启用过滤器
                                    if (workBook?.Worksheets[0]?.AutoFilters?.FilterRange != null)
                                    {
                                        workBook.Worksheets[0].AutoFilters.FilterRange = workBook.Worksheets[0].UsedRange;
                                    }
                                    workBook?.SaveAs(saveFilePath);
                                    if (File.Exists(saveFilePath))
                                    {

                                        var confirmRes = LocalizationResource.StringFormatArgs("已将文件导出至：\r\n{0}\r\n是否需要打开导出的文件?", saveFilePath)
                                            .ShowDialogMessageBoxQuestion("导出成功",
                                            messageBoxButton: MessageBoxButton.YesNo);
                                        if (confirmRes.Result == ButtonResult.Yes)
                                        {
                                            ProcessHelper.OpenFile(saveFilePath);
                                        }
                                    }
                                    else
                                    {
                                        LocalizationResource.StringFormatArgs("未能将文件导出至：\r\n{0}\r\n请查证！", saveFilePath).ShowDialogMessageBoxError();
                                    }
                                }
                                else
                                {
                                    LocalizationResource.GetResourceValue("没有需要导出的数据，请查证！").ShowDialogMessageBoxInfo();
                                }
                            }
                        }
                    }
                    else
                    {
                        LocalizationResource.GetResourceValue("没有获取到导出的信息，请查证！").ShowDialogMessageBoxInfo();
                    }
                }
                catch (Exception ex)
                {
                    ex.ShowDialogMessageBoxException(LocalizationResource.GetResourceValue("导出数据到Excel出现异常"));
                }
            }
        }

        private static void Fe_Unloaded(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement fe)
            {
                fe.Loaded -= Fe_Loaded;
                fe.MouseLeftButtonDown -= Fe_MouseLeftButtonDown;
                fe.Unloaded -= Fe_Unloaded;
            }
        }

        private static void Fe_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement fe)
            {
                fe.Unloaded -= Fe_Unloaded;
                fe.PreviewMouseLeftButtonDown -= Fe_MouseLeftButtonDown;
                fe.Unloaded += Fe_Unloaded;
                fe.PreviewMouseLeftButtonDown += Fe_MouseLeftButtonDown;
            }
        }

        #endregion 数据源 - 依赖属性
    }
}
